import sys
from PySide6.QtCore import QObject, Signal, QMutex,QMutexLocker

from app.core.img_opencv import *
from app.core.key_board import *
from app.core.img_ocr import *

from app.work.work_pet import *
from app.work.work_role import *
from app.work.work_week import *
from app.work.work_season import *
from app.work.work_public import *
from app.work.work_customize import *


if getattr(sys, 'frozen', False): 
    root_dir = Path(sys.executable).parent 
else:
    root_dir=Path(__file__).resolve().parent.parent

class ConnectorService(QObject):
    logMessage = Signal(str)
    get_scale = Signal(float)
    finished = Signal()
# region 初始化
    def __init__(self,key_map):
        super().__init__() 
        self.mutex = QMutex()  # 创建互斥锁实例
        self._running = True
        self.key_map = key_map
        self._tasks={
            'wlt': self.wlt_pb_clicked,
            'zld': self.zld_pb_clicked,
            'Mysterious_Merchant': self.Mysterious_Merchant_pb_clicked,
            'baoku': self.baoku_pb_clicked,
            'synthesis_gemstone': self.synthesis_gemstone_pb_clicked,
            'signin': self.signin_pb_clicked,
            'donate': self.donate_pb_clicked,
            'zhuzhan': self.zhuzhan_pb_clicked,
            'douchong': self.douchong_pb_clicked,
            'wanshou': self.wanshou_pb_clicked,
            'scale': self.scale_match_pb_clicked,
            'every_day': self.every_day_pb_clicked,
            'douchong_challenge': self.douchong_challenge_pb_clicked,
            'record': self.record_pb_clicked,
            'execute': self.execute_pb_clicked,
        }
    def stop(self):
        """安全停止所有任务"""
        with QMutexLocker(self.mutex):
            self._running = False
            self.logMessage.emit("正在停止当前任务...")

    def execute_task(self, task_name: str, params: dict):
        """执行具体任务"""
        self._running = True
        try:
            if task_name in self._tasks:
                self._tasks[task_name](**params)
            else:
                self.logMessage.emit(f"未知任务: {task_name}")

        except Exception as e:
            self.logMessage.emit(f"任务执行出错: {str(e)}")
        finally:
            self.finished.emit()
# region 万灵塔
    def wlt_pb_clicked(self,spin_box_value, selected_index, scale):
        """
        万灵塔
        """
        # 前置校验
        if not is_image_now('app_img/pet_challenge/2.png', threshold=0.7, scale=scale):
            back_to_main(scale=scale)

            if(not if_exist_click_image('app_img/public_img/pet_challenge.png', scale=scale)):
                self.logMessage.emit("请返回游戏主界面")
                return
            wait_image('app_img/pet_challenge/2.png', threshold=0.7, scale=scale)
        elif not if_exist_click_image('app_img/pet_challenge/3_1.png',threshold=0.8 ,scale=scale):
                click_image('app_img/pet_challenge/3_2.png', threshold=0.7, scale=scale)

        # 正式开始
        wlt_work(spin_box_value, selected_index, scale)

        # 结束
        back_to_main(scale=scale)
        self.logMessage.emit("万灵塔挑战完成")
# endregion

# region 葬灵洞
    def zld_pb_clicked(self, scale):
        """
        葬灵洞
        """
        # 前置校验
        back_to_main(scale=scale)
        if(not if_exist_click_image('app_img/public_img/pet_challenge.png', scale=scale)):
            self.logMessage.emit("请返回游戏主界面")
            return
        
        # 正式开始
        zld_work(scale)
        
        # 结束
        back_to_main(scale=scale)
        self.logMessage.emit("葬灵洞挑战完成")
# endregion

# region 斗宠挑战
    def douchong_challenge_pb_clicked(self, selected_index,scale):
        """
        斗宠挑战
        """
        # 前置校验        
        back_to_main(scale=scale)
        if(not if_exist_click_image('app_img/public_img/douchong_challenge.png', threshold=0.7, scale=scale)):
            self.logMessage.emit("请返回游戏主界面")
            return

        # 正式开始
        douchong_work(selected_index,scale)
        
        back_to_main(scale=scale)
        self.logMessage.emit("斗宠挑战完成")
# endregion

# region 神秘商人
    def Mysterious_Merchant_pb_clicked(self,buy_index,scale):
        """
        神秘商人
        """
        # 前置校验
        back_to_main(scale=scale)
        if not HomeCity(scale=scale):
            self.logMessage.emit("请返回游戏主界面")
            return

        # 正式开始
        Mysterious_Merchant_work(buy_index,scale,self.key_map)

        # 结束
        back_to_main(scale=scale)
        self.logMessage.emit("神秘商人购买完成")
# endregion     

# region 宝库
    def baoku_pb_clicked(self,scale):
        """
        宝库
        """
        # 前置校验
        back_to_main(scale)
        if (not if_exist_click_image('app_img/public_img/backpack.png', threshold=0.7, scale=scale)):
            self.logMessage.emit("请返回游戏主界面")
            return
        
        # 正式开始
        baoku_work(scale)
                
        # 结束
        back_to_main(scale)
        self.logMessage.emit("宝库开启成功")
# endregion

# region 宝石合成
    def synthesis_gemstone_pb_clicked(self,check_boxes,scale):
        """
        宝石合成
        """
        # 前置校验
        back_to_main(scale=scale)
        if not if_exist_click_image('app_img/synthesis_gemstone/1.png', threshold=0.7, scale=scale):
            self.logMessage.emit("请返回游戏主界面")
            return

        # 正式开始
        gemstone_work(check_boxes,scale)
        
        # 结束
        back_to_main(scale=scale)
        self.logMessage.emit("宝石合成完成")
# endregion

# region每日签到
    def signin_pb_clicked(self,scale):
        """
            每日签到
        """
        # 前置校验
        back_to_main(scale)
        if not if_exist_click_image('app_img/sign_in/1.png', threshold=0.7, scale=scale):
            self.logMessage.emit("请返回游戏主界面")

        # 正式开始
        signin_work(scale)

        # 结束
        back_to_main(scale)
        self.logMessage.emit("每日签到完成")
# endregion

# region 联盟捐献
    def donate_pb_clicked(self,donate_count,scale):
        """
            联盟捐献
        """
        # 前置校验
        back_to_main(scale=scale)
        if not if_exist_click_image('app_img/donate/1.png', threshold=0.7, scale=scale):
            self.logMessage.emit("请返回游戏主界面")
            return
        
        # 正式开始
        donate_work(donate_count,scale)

        # 结束
        back_to_main(scale=scale)
        self.logMessage.emit("联盟捐献完成")
# endregion

# region 助战
    def zhuzhan_pb_clicked(self,kunrun_map_num,scale):
        """
        助战
        """
        # 前置校验
        back_to_main(scale=scale)
        if not if_exist_click_image('app_img/public_img/role_challenge.png', threshold=0.7, scale=scale):
            self.logMessage.emit("请返回游戏主界面")
            return
        
        # 正式开始
        zhuzhan_work(kunrun_map_num,scale,self.key_map)

        back_to_main(scale=scale)
        self.logMessage.emit("助战完成")
# endregion

# region 斗宠反击
    def douchong_pb_clicked(self,continue_execution,scale):
        """
        斗宠反击
        """
        # 前置校验
        if not continue_execution:
            self.logMessage.emit("取消反击")
            return
        
        back_to_main(scale=scale)
        if(not if_exist_click_image('app_img/public_img/douchong_challenge.png', threshold=0.7, scale=scale)):
            self.logMessage.emit("请返回游戏主界面")
            return

        # 正式开始
        dc_counterattack_work(scale)
                
        # 结束
        back_to_main(scale=scale)
        self.logMessage.emit("斗宠反击完成")
# endregion 

# region 万兽争锋
    def wanshou_pb_clicked(self,scale):
        """
        万兽争锋
        """
        # 前置校验
        back_to_main(scale=scale)
        if (not if_exist_click_image('app_img/wszf_challenge/1.png', threshold=0.6, scale=scale)):
            self.logMessage.emit("请返回游戏主界面\n或者暂未到达活动时间")
            return
        
        # 正式开始
        success_num = wanshou_work(scale)
        
        # 结束
        back_to_main(scale=scale)
        if(success_num==15):
            self.logMessage.emit("万兽争锋15次成功")
        else:
            self.logMessage.emit("已经失败5次，请提升战力或者调整阵容再尝试")
# endregion

# region 匹配缩放
    def scale_match_pb_clicked(self):
        """
        匹配缩放
        """
        scale_num = found_scale(
            'app_img/scale_match/scale_match_2.png',
              threshold=0.9
            )
        if scale_num == -1:
            self.logMessage.emit("未找到匹配的缩放比例")
        else:
            self.get_scale.emit(scale_num)
            self.logMessage.emit("画面缩放匹配成功，缩放比例：" + str(scale_num))
# endregion
# region 一键日常
    def every_day_pb_clicked(self,scale):
        """
            一键日常
        """
        import configparser
        from pathlib import Path
        config = configparser.ConfigParser()
        config_file = Path(__file__).resolve().parent.parent / 'config.ini'

        if config_file.exists():
            config.read(config_file, encoding='utf-8')
            merchant_buy_index = config.getint('SETTING', '神秘商人', fallback=1)
            wlt_floors_str = config.get('SETTING', '万灵塔', fallback='1,2,3,4')
        else:
            merchant_buy_index = 1
            wlt_floors_str = '1,2,3,4'

       # 解析万灵塔层数
        try:
            wlt_floors = [int(floor.strip()) for floor in wlt_floors_str.split(',')]
        except ValueError:
            wlt_floors = [1,2,3,4] 

        self.signin_pb_clicked(scale=scale)

        self.baoku_pb_clicked(scale=scale)

        self.Mysterious_Merchant_pb_clicked(buy_index=merchant_buy_index,scale=scale)

        for floor in wlt_floors:
            self.wlt_pb_clicked(spin_box_value=1,selected_index=floor,scale=scale)

        self.zld_pb_clicked(scale=scale)

        self.donate_pb_clicked(donate_count=5,scale=scale)
# endregion

# region 录制
    def record_pb_clicked(self,scale):
        """
        录制
        """
        start_recording = record_events()
        start_recording()
        self.logMessage.emit("录制完成" )

# endregion

# region 执行
    def execute_pb_clicked(self,execute_count,filename,scale):

        """
        执行
        """
        print(filename)
        for _ in range(execute_count):
            execute_events(filename)
        self.logMessage.emit("执行完成")
# endregion
